package com.yang.sso.server.security;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.yang.sso.server.properties.SecurityProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

import java.util.List;

/**
 * @author zhouyang
 * @version v1.1
 * @date 2024/9/24 14:15
 * @description Security安全入口配置
 */
@Slf4j
@EnableWebSecurity
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
public class WebSecurityConfig {

    private final SecurityProperties securityProperties;


    /**
     *  Spring Security 过滤链配置（此处是纯Spring Security相关配置）
     */
    @Bean
    @Order(2)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
            throws Exception {
        List<String> whitePaths = securityProperties.getWhitePaths();
        http
                .authorizeHttpRequests((authorize) -> {
                            if (CollectionUtil.isNotEmpty(whitePaths)) {
                                log.info("放行路由:{}",whitePaths);
                               authorize.requestMatchers(Convert.toStrArray(whitePaths)).permitAll();
                            }
                            authorize.anyRequest().authenticated();
                        }

                )
                .formLogin(Customizer.withDefaults());

        return http.build();
    }
}
